﻿using Microsoft.AspNetCore.Http;
using QRCoder;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;

namespace FlashPay.Util
{
    public static class WebUtil
    {
        /// <summary>
        ///  获取客户Ip
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static string GetUserIp(this HttpContext context)
        {
            var ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
            if (string.IsNullOrEmpty(ip))
            {
                ip = context.Connection.RemoteIpAddress.ToString();
            }
            return ip;
        }


        /// <summary>
        /// 过滤特殊字符，保留中文，字母，数字，和-
        /// </summary>
        /// <param name="inputValue">输入字符串</param>
        /// <remarks>发件和收件详细地址有这种情况：“仓场路40-73号迎园新村四坊69号202室”，这种带有-的特殊字符不需要过滤掉</remarks>
        /// <returns></returns>
        public static string FilterChar(string inputValue)
        {
            if (!string.IsNullOrEmpty(inputValue)) {
                return Regex.Match(inputValue, "[A-Za-z0-9\u4e00-\u9fa5-]+").Value;
            }
            return inputValue;
            // return Regex.Replace(inputValue, "[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）&mdash;|{}【】；‘’，。/*-+]+", "", RegexOptions.IgnoreCase);
            //if (Regex.IsMatch(inputValue, "[A-Za-z0-9\u4e00-\u9fa5-]+"))
            //{
                
            //}
            //return "";
        }

        /// <summary>
        /// 是否为日期型字符串
        /// </summary>
        /// <param name="strDate">日期字符串(2008-05-08)</param>
        /// <returns></returns>
        public static bool IsDate(string strDate)
        {
            return Regex.IsMatch(strDate, @"^((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-9]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))$");
        }

        /// <summary>
        /// 处理银行卡号
        /// </summary>
        /// <param name="strDate">日期字符串(2008-05-08)</param>
        /// <returns></returns>
        public static string SetCardNumber(string cardNumber)
        {
            if (string.IsNullOrEmpty(cardNumber)) return "";
            var StaNum = cardNumber.Substring(0, 4);
            var EndNum = cardNumber.Substring(cardNumber.Length - 4);
            return StaNum + "***********" + EndNum;
        }

        /// <summary>
        /// 处理银行卡号
        /// </summary>
        /// <param name="strDate">日期字符串(2008-05-08)</param>
        /// <returns></returns>
        public static string CardType(sbyte cardType)
        {
            var result = "";

            switch (cardType)
            {
                case 1:
                    result = "收款卡";
                    break;
                case 2:
                    result = "中转卡";
                    break;
                case 3:
                    result = "付款卡";
                    break;
                case 4:
                    result = "备用卡";
                    break;
                case 5:
                    result = "储备卡";
                    break;
                case 6:
                    result = "下发储备卡";
                    break;
                case 7:
                    result = "付款储备卡";
                    break;
                case 8:
                    result = "安全卡";
                    break;
                case 99:
                    result = "作废卡";
                    break;
            }
            return result;
        }

        /// <summary>
        /// 处理银行卡号
        /// </summary>
        /// <param name="strDate">日期字符串(2008-05-08)</param>
        /// <returns></returns>
        public static string Name(string name)
        {
            if (string.IsNullOrEmpty(name)) return "";
            return  name.Substring(0,name.Length - (name.Length-1))+ "**";
        }

        public static void CurrentDirectory()
        {
            var path = Directory.GetCurrentDirectory();
        }

        /// <summary>
        /// 转半角
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static String ToDBC(String str)
        {
            char[] c = str.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] == 12288)
                {
                    c[i] = (char)32;
                    continue;
                }
                if (c[i] > 65280 && c[i] < 65375)
                    c[i] = (char)(c[i] - 65248);
            }
            return new String(c);
        }

        /// <summary>
        /// 生成二维码
        /// </summary>
        /// <param name="content">内容</param>
        /// <param name="version">版本 1 ~ 40</param>
        /// <param name="pixel">像素点大小</param>
        /// <param name="icon_path">图标路径</param>
        /// <param name="icon_size">图标尺寸</param>
        /// <param name="icon_border">图标边框厚度</param>
        /// <param name="white_edge">二维码白边</param>
        /// <returns>位图</returns>
        public static Bitmap QRCode(string content, int version, int pixel, string icon_path, int icon_size, int icon_border, bool white_edge)
        {

            QRCodeGenerator qRCodeGenerator = new QRCodeGenerator();

            QRCodeData qRCodeData = qRCodeGenerator.CreateQrCode(content, QRCodeGenerator.ECCLevel.M, true, true, QRCodeGenerator.EciMode.Utf8, version);

            QRCode qRCode = new QRCode(qRCodeData);

            Bitmap bitmap = qRCode.GetGraphic(pixel, Color.Black, Color.White, new Bitmap(icon_path), icon_size, icon_border, white_edge);

            return bitmap;

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="bmp"></param>
        /// <returns></returns>
        public static string ImgToBase64String(Bitmap bmp)
        {
            try
            {
                MemoryStream ms = new MemoryStream();
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
                return Convert.ToBase64String(arr);
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        /// <summary>
        /// 对Url进行解码,对于javascript的encodeURIComponent函数编码参数,应使用utf-8字符编码来解码
        /// </summary>
        /// <param name="url">url</param>
        public static string UrlDecode(string url)
        {
            return HttpUtility.UrlDecode(url);
        }

        /// <summary>
        /// 组装参数
        /// </summary>
        /// <param name="param">参数</param>
        /// <returns>参数字符串</returns>
        public static string buildParamStr(string reqeustUrl, Dictionary<String, String> param)
        {
            String paramStr = String.Empty;
            foreach (var key in param.Keys.ToList())
            {
                if (param.Keys.ToList().IndexOf(key) == 0)
                {
                    paramStr += (key + "=" + param[key]);
                }
                else
                {
                    paramStr += ("&" + key + "=" + param[key]);
                }
            }
            return reqeustUrl + paramStr;
        }

        public static string ReplaceLevel(string str)
        {
            str = str.Replace("A", "1x");
            str = str.Replace("B", "2x");
            str = str.Replace("C", "3x");
            str = str.Replace("D", "4x");
            str = str.Replace("E", "5x");
            str = str.Replace("F", "6x");
            str = str.Replace("G", "7x");
            str = str.Replace("H", "8x");
            str = str.Replace("I", "9x");
            str = str.Replace("J", "10x");
            str = str.Replace("K", "11x");
            str = str.Replace("L", "12x");
            str = str.Replace("X", "x");


            return str;
        }
    }

}
